﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Qetza.TeamFoundation.WorkItemQuery.Admin
{
    /// <summary>
    /// Provides extension methods for the <see cref="String"/> class.
    /// </summary>
    public static class StringExtensions
    {
        #region Methods

        /// <summary>
        /// Breaks the specified string into multiple line using the specified line length.
        /// </summary>
        /// <param name="source">
        /// The string to break into lines.
        /// </param>
        /// <param name="maxLineLength">
        /// The maximum line length in character.
        /// </param>
        /// <returns>
        /// An array of lines.
        /// </returns>
        public static string[] Break(this string source, int maxLineLength)
        {
            // validate parameters
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            // break source text into lines
            var lines = new List<string>();
            var separatorIndex = 0;
            var startIndex = 0;
            var charCount = 0;

            for (var i = 0; i < source.Length; ++i)
            {
                var c = source[i];

                if (char.IsSeparator(c))
                {
                    separatorIndex = i;
                }

                ++charCount;
                if (charCount >= maxLineLength)
                {
                    if (separatorIndex <= startIndex)
                    {
                        separatorIndex = i;
                    }

                    lines.Add(source.Substring(startIndex, separatorIndex - startIndex));

                    startIndex = separatorIndex;
                    while (startIndex < source.Length && char.IsWhiteSpace(source, startIndex))
                    {
                        ++startIndex;
                    }

                    i = startIndex;
                    charCount = 0;
                }
            }

            if (startIndex < source.Length)
            {
                lines.Add(source.Substring(startIndex));
            }

            return lines.ToArray();
        }

        #endregion
    }
}
